<template>
  <!--查看地图组件-->
  <div class="app-container">

    <van-popup
      v-model="baiduMaptwo"
      position="right"
      :style="{ height: '100%', width: '100%' }"
    >
      <div class="topPosition" ref="topPosition" style="height:0px;background-color: transparent;">
        <div class="iconSpan">
          <van-icon name="cross" size="24px" @click="close" style="margin-top: 8px;"/>
        </div>
      </div>

      <div :style="PeoplesBoxStyle">
        <!-- 要设置div的高度 -->
        <div id="map-container" :style="containerStyle" />
        <!--<p>实际定位：{{address}}</p>-->
        <!--<p>当前位置：{{address2}}</p>-->
        <!--<p>周围地点中对比得到距离定位点最近的：{{address3}}</p>-->

        <div style="height: 180px">
          <van-cell-group>
            <van-cell :label="'经度：'+ newposPoint.longitude + ' , ' + '纬度：'+ newposPoint.latitude">
              <!-- 使用 title 插槽来自定义标题 -->
              <template #title>
                <span class="custom-title">{{address2}} </span>
                <van-tag type="success"> 当前位置</van-tag>
              </template>
            </van-cell>
          </van-cell-group>

          <van-cell-group>
            <van-cell :label="'经度：'+ address3.point.lng + ' , ' + '纬度：'+ address3.point.lat">
              <!-- 使用 title 插槽来自定义标题 -->
              <template #title>
                <span class="custom-title">{{address3.title}} </span>
                <van-tag type="success"> 附近位置</van-tag>
              </template>
            </van-cell>
          </van-cell-group>
        </div>
      </div>
    </van-popup>

  </div>
</template>


<script>
  import Vue from 'vue';
  import BMap from 'BMap'
  import { Popup } from 'vant';
  import { Icon } from 'vant';
  import { Cell, CellGroup } from 'vant';
  import { Tag } from 'vant';

  Vue.use(Tag);
  Vue.use(Cell);
  Vue.use(CellGroup);
  Vue.use(Icon);
  Vue.use(Popup);

  export default {
    props:{
      posPoint:{
        type: Object,
        default: null
      },
      checkPointList:{
        type: Array,
        default: ()=>[]
      },
    },
    data() {
      return {
        address: '默认位置',
        address2: '默认位置',
        address3: {
          title:"默认位置",
          point:{
            lng:"",
            lat:""
          }
        },
        newposPoint:{
          longitude:"",
          latitude:""
        },
        containerStyle:{
          width:"100%",
          height:"500px"
        },
        PeoplesBoxStyle: {
          position: "absolute",
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          "z-index": 100,
          // overflow: "auto"
        },
        baiduMaptwo:false,
        form: {
          address: '', // 详细地址
          addrPoint: { // 详细地址经纬度
            lng: 0,
            lat: 0
          }
        },
        map: '', // 地图实例
        mk: '', // Marker实例
        locationPoint: null
      }
    },
    async mounted() {
      // await loadBMap('htgznmBQ0fTOjLFTz98yrUb5IiABdXOG') // 加载引入BMap
      // this.initMap()
      // this.createMap()
      let winHeight = document.documentElement.clientHeight || document.body.clientHeight;
      this.containerStyle.height = winHeight - 180 + "px";

    },

    methods: {
      createMap () {
       console.log("创建地图");
        var that = this
        // 创建Map实例
        var map = new BMap.Map('map')
        // 初始化地图,设置中心点坐标和地图级别
        map.centerAndZoom(new BMap.Point(116.404, 39.915), 17)
        //添加地图类型控件
        map.addControl(new BMap.MapTypeControl({
          mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP]
        }))
        // 设置地图显示的城市 此项是必须设置的
        map.setCurrentCity('北京')

        /* eslint-enable */
        var geoc = new BMap.Geocoder()
        var geolocation = new BMap.Geolocation()
        geolocation.getCurrentPosition(function (r) {
          if (this.getStatus() === BMAP_STATUS_SUCCESS) {
            var mk = new BMap.Marker(r.point, { enableDragging: true })
            map.addOverlay(mk)
            map.panTo(r.point)
            console.log('您的位置：' + r.point.lng + ',' + r.point.lat)

            var pt = r.point
            geoc.getLocation(pt, function (rs) {
              var addComp = rs.addressComponents
              mk.setPosition(r.point)
              that.address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber
            })
          } else {
            console.log('failed' + this.getStatus())
          }
        }, { enableHighAccuracy: true })
      },
      // 初始化地图
      initMap() {
        var that = this;
        // console.log("传入的坐标："+JSON.stringify(this.posPoint));
        // 1、挂载地图
        this.map = new BMap.Map('map-container', { enableMapClick: false });
        let point = new BMap.Point(this.posPoint.longitude, this.posPoint.latitude);
        this.newposPoint = this.posPoint;
        this.map.centerAndZoom(point, 17);

        // 3、设置图像标注
        this.mk = new BMap.Marker(point);
        this.map.addOverlay(this.mk);

        // 4、添加（右上角）平移缩放控件
        this.map.addControl(new BMap.NavigationControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL }))
        // 根据当前定位点获取地址
        that.getAddrByPoint(point);
        // 显示考勤点以及范围
        this.greatCircle();
        this.map.enableContinuousZoom(); //开启缩放中心不变


        // 5、添加（右下角）定位控件
        // var geolocationControl = new BMap.GeolocationControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT })
        // geolocationControl.addEventListener('locationSuccess', function(e) {
        //   consolo.log("定位成功");
        //   that.getAddrByPoint(e.point)
        // })
        // geolocationControl.addEventListener('locationError', function(e) {
        //   consolo.log("定位失败");
        // })
        // this.map.addControl(geolocationControl);

        // 6、浏览器定位
        // this.geolocation();

        // 7、绑定点击地图任意点事件
        // this.map.addEventListener('click', function(e) {
        //   that.getAddrByPoint(e.point)
        // })
      },
      // 获取两点间的距离
      getDistancs(pointA, pointB) {
        return this.map.getDistance(pointA, pointB).toFixed(2)
      },
      // 根据考勤点画圆显示半径
      greatCircle() {
        let that = this;
        console.log(that.checkPointList);
        // let myIcon = new BMap.Icon(require("@/assets/zh.png"), new BMap.Size(40, 40),{imageOffset: new BMap.Size(40,40)});
        if(that.checkPointList.length != 0){
          var len = that.checkPointList.length;
          for (var i = 0; i < len; i++) {
            let item = that.checkPointList[i];
            let point = new BMap.Point(item.longitude, item.latitude);
            let range = item.cardRange;
            let circle = new BMap.Circle(point, range, {
              fillColor: "blue",    //圆形填充颜色
              strokeWeight: 1,    //圆形边线宽度，大于1的整数
              fillOpacity: 0.3,   //圆形填充的透明度
              strokeOpacity: 0.3 //圆形边线透明度
            });
            // let newmk = new BMap.Marker(point,{
            //   icon: myIcon
            // });
            // that.map.addOverlay(newmk);
            that.map.addOverlay(circle);
          }
        }

      },
      // 浏览器定位函数
      geolocation() {
        var that = this
        var geolocation = new BMap.Geolocation()
        geolocation.getCurrentPosition(function(res) {
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            that.getAddrByPoint(res.point)
            that.locationPoint = res.point
          } else {
            alert('failed' + this.getStatus())
            that.locationPoint = new BMap.Point(113.3324436, 23.1315381)
          }
        }, { enableHighAccuracy: true })
      },
      // 2、逆地址解析函数
      getAddrByPoint(point) {
        var that = this
        var geco = new BMap.Geocoder()
        geco.getLocation(point, function(res) {
          console.log(res)
          that.mk.setPosition(point)
          that.map.panTo(point)
          that.form.address = res.address;
          // that.address = "实际定位：" + res.addressComponents.city + res.addressComponents.district + res.addressComponents.street + res.addressComponents.streetNumber

          if (res.surroundingPois[0].title.indexOf("上海大众") > -1){
            that.address2 = res.surroundingPois[0].title.length < 4?"上汽大众":  "上汽大众"+ res.surroundingPois[0].title.slice(4,res.surroundingPois[0].title.length -1);
          } else {
            that.address2 = res.surroundingPois[0].title;
          }
          that.comparePoint(point,res.surroundingPois);
          that.form.addrPoint = point;
        })
      },
      // 8-1、地址搜索
      querySearchAsync(str, cb) {
        var options = {
          onSearchComplete: function(res) {
            var s = []
            if (local.getStatus() == BMAP_STATUS_SUCCESS) {
              for (var i = 0; i < res.getCurrentNumPois(); i++) {
                s.push(res.getPoi(i))
              }
              cb(s)
            } else {
              cb(s)
            }
          }
        }
        var local = new BMap.LocalSearch(this.map, options)
        local.search(str)
      },
      // 8-2、选择地址
      handleSelect(item) {
        this.form.address = item.address + item.title
        this.form.addrPoint = item.point
        this.map.clearOverlays()
        this.mk = new BMap.Marker(item.point)
        this.map.addOverlay(this.mk)
        this.map.panTo(item.point)
      },
      onSubmit() {
        console.log(this.form)
      },
      open(){
        this.baiduMaptwo = true;
        this.$nextTick(()=>{
          // this.createMap();
          this.initMap()
        })

      },
      close(){
        this.baiduMaptwo = false;
      },
      // 坐标比对
      comparePoint(point,pointList) {
        let that = this;
        // 判断，如果匹配设置好的打卡点范围，就返回2，不匹配就返回3
        let len = pointList.length;
        let arr = [];
        for (let i = 0; i < len; i++) {
          let item = pointList[i];
          let centerPoint = new BMap.Point(item.point.lng, item.point.lat);   //中心点  121.51250578039334,lat: 31.31992884580855
          let positionPoint = new BMap.Point(point.lng, point.lat);   //定位点
          // console.log("定位点：" + JSON.stringify(positionPoint));
          let distance = that.map.getDistance(centerPoint, point);
          // alert("距离为2：" + distance);
          arr.push(parseInt(distance));
          // console.log(arr);
          let little = arr.filter((el,index)=>{
            let lit = arr[0];
            if (lit > arr[index]){
              lit = arr[index]
            }
            return lit
          })
          // console.log(little)
        }
        let recent = pointList[0];
        for (let j = 0; j < arr.length; j++){
          let little = arr[0];
          if (little > arr[j]){
            recent = pointList[j]
          }
        }
        console.log(recent);
        if (recent.title.indexOf("上海大众") > -1){
          recent.title = recent.title.length < 4?"上汽大众": "上汽大众"+ recent.title.slice(4,recent.title.length -1);
        }
        that.address3 = recent;   //recent.title  地址

      },
    }
  }
</script>

<style lang="scss" scoped>
  .autoAddressClass{
    li {
      i.el-icon-search {margin-top:11px;}
      .mgr10 {margin-right: 10px;}
      .title {
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .address {
        line-height: 1;
        font-size: 12px;
        color: #b4b4b4;
        margin-bottom: 5px;
      }
    }
  }
  .iconSpan{
    width: 40px;
    height: 40px;
    border-radius: 20px;
    text-align: center;
    background-color: #fff;
    box-shadow: 1px 1px 8px #c5c5c5;
    margin: 20px 10px;
    float: right;
  }
  .backicon{
    width: auto;
    padding: 10px;
    position: absolute;
    right: 0;
    top: 440px;
    border-radius: 4px;
    margin-right: 10px;
    text-align: center;
    background-color: #fff;
    box-shadow: 1px 1px 8px #c5c5c5;
    margin: 10px;
  }
  /* 这个样式可以去除地图底部logo */
  .anchorBL{
    display:none;
  }
</style>

